//
//  RssFeedViewController.m
//  Lettore RSS Feed
//
//  Created by Dario Trisciuoglio on 09/06/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "RssFeedViewController.h"
#import "ArticoloCommentiViewController.h"
#import "RssFeedCell.h"
#import "AutoDownloadImageView.h"

@implementation RssFeedViewController
@synthesize spinner;
@synthesize spinnerView;

-(void)addIndicator{
    [self.view addSubview:spinnerView];
    [spinner startAnimating];
    [self.view setUserInteractionEnabled:NO];
}

-(void)removeIndicator{
    [spinner stopAnimating];
    [spinner release];    
    [spinnerView removeFromSuperview];
    [spinnerView release];
    [self.view setUserInteractionEnabled:YES];
}

- (void)applicaColore {
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:1.0];
	self.spinnerView.backgroundColor = [UIColor clearColor];
	[UIView commitAnimations];
}

- (void)viewDidLoad {
	self.title = @"Microta)k";
    URLparser = mobile_server_elenco_news;
	[self parseXMLFileAtURL:URLparser];
    [self addIndicator];
    [super performSelector:@selector(controlloDownloadXML) withObject:URLparser afterDelay:0.01];
    [super viewDidLoad];
}

- (void)controlloDownloadXML{
	[self parseXMLFileAtURL:URLparser];
    [self applicaColore];
    [super performSelector:@selector(removeIndicator) withObject:URLparser afterDelay:0.01];
    [self.tableView reloadData];
}

- (void)parseXMLFileAtURL:(NSString *)URL {
	// inizializziamo la lista degli elementi
	elencoFeed = [[NSMutableArray alloc] init];
	// dobbiamo convertire la stringa "URL" in un elemento "NSURL"
	NSURL *xmlURL = [NSURL URLWithString:URL];
	// inizializziamo il nostro parser XML
	rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
	[rssParser setDelegate:self];
	// settiamo alcune proprietà
	[rssParser setShouldProcessNamespaces:NO];
	[rssParser setShouldReportNamespacePrefixes:NO];
	[rssParser setShouldResolveExternalEntities:NO];
	// avviamo il parsing del feed RSS
	[rssParser parse];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{			
	currentElement = [elementName copy];
	if ([elementName isEqualToString:@"item"]) {
		// inizializza tutti gli elementi
		item = [[NSMutableDictionary alloc] init];
		currentTitle = [[NSMutableString alloc] init];
		currentDate = [[NSMutableString alloc] init];
		currentSummary = [[NSMutableString alloc] init];
        currentSummaryLight = [[NSMutableString alloc] init];
        currentImageUrl = [[NSMutableString alloc] init];
		currentLink = [[NSMutableString alloc] init];
	}
    
}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{     
	
	if ([elementName isEqualToString:@"item"]) {
		/* salva tutte le proprietà del feed letto nell'elemento "item", per poi inserirlo nell'array "elencoFeed" */
		[item setObject:currentTitle forKey:@"title"];
		[item setObject:currentLink forKey:@"link"];
		[item setObject:currentSummary forKey:@"description"];
		[item setObject:currentSummaryLight forKey:@"descriptionLIGHT"];
        [item setObject:currentImageUrl forKey:@"imageURL"];
        [item setObject:currentDate forKey:@"date"];
		[elencoFeed addObject:[item copy]];
        // settiamo la data dell'ultimo refresh (in questo caso è nil, non ci sono date precedenti)
        [self.refreshHeaderView setLastRefreshDate:nil];

	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{;
	// salva i caratteri per l'elemento corrente
	if ([currentElement isEqualToString:@"title"]){
		[currentTitle appendString:string];
	} else if ([currentElement isEqualToString:@"link"]) {
		[currentLink appendString:string];
	} else if ([currentElement isEqualToString:@"description"]) {
		[currentSummary appendString:string];
	} else if ([currentElement isEqualToString:@"descriptionLIGHT"]) {
		[currentSummaryLight appendString:string];
	} else if ([currentElement isEqualToString:@"imageURL"]) {
		[currentImageUrl appendString:string];
	} else if ([currentElement isEqualToString:@"pubDate"]) {
		[currentDate appendString:string];
	}
    
}

- (void)reloadTableViewDataSource{
    //Nuovo parsing XML per aggiornare il Feed
	NSString *path = mobile_server_elenco_news;
    [super performSelector:@selector(parseXMLFileAtURL:) withObject:path];
}

- (void)dataSourceDidFinishLoadingNewData{
    // settiamo la data corrente come ultimo refresh
    [refreshHeaderView setCurrentDate];
    [super dataSourceDidFinishLoadingNewData];
    [self.tableView reloadData];

}

- (void) parserDidEndDocument:(NSXMLParser *)parser {
    [super performSelector:@selector(dataSourceDidFinishLoadingNewData) withObject:nil afterDelay:0.0];
    [parser release];
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

#pragma mark - UITableViewDelegate Methods

// prende l'altezza della cella nello xib 
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //NSLog(@"%@", elencoFeed);
    return [elencoFeed count];

}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"RssFeedCell";
	
    RssFeedCell *cell = (RssFeedCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        
		NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"RssFeedCell" owner:self options:nil];
		
		for (id currentObject in topLevelObjects){
			if ([currentObject isKindOfClass:[UITableViewCell class]]){
				cell =  (RssFeedCell *) currentObject;
				break;
			}
		}
	}
    
    // Metodo della classe AutoDownloadImageView molto meglio funziona
    id path = [[elencoFeed objectAtIndex:indexPath.row] objectForKey:@"imageURL"];
    path = [path stringByReplacingOccurrencesOfString:@" " withString:@""];
	path = [path stringByReplacingOccurrencesOfString:@"\n" withString:@""];
	path = [path stringByReplacingOccurrencesOfString:@"	" withString:@""];
    
    //converto la stringa del link affinchè sia letta e caricata al posto dell'immagine
    NSURL *url = [NSURL URLWithString:path];
	//controllo se l'url sia valida
    //if(!url) { NSLog(@"Errore nell'url"); exit(0);}
    AutoDownloadImageView *img = [[AutoDownloadImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 160)URL:url persistency:YES forceDownload:NO];
	[img setDelegate:self];
    [cell.contentView addSubview:img];
    //setta lo stile con cui vengono selezionate le righe
    //[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    //cell.selectionStyle = UITableViewCellSelectionStyleGray;
    //setta il stile con cui vengono selezionate le righe
    UIImageView *selBgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cella_bg.png"]];
    cell.selectedBackgroundView = selBgView;
    cell.titolo.text = [[elencoFeed objectAtIndex:indexPath.row] objectForKey:@"title"];
	cell.link.text = [[elencoFeed objectAtIndex:indexPath.row] objectForKey:@"link"];
    cell.descrizione.text = [[elencoFeed objectAtIndex:indexPath.row] objectForKey:@"description"];
    [cell retain];
    return cell;

}

-(void)autoDownload:(AutoDownloadImageView *)autoDowload didFailWithError:(NSError *)error {
	NSLog(@"SOMETHING WRONG");
}

-(void)autoDownloadImageViewFinishDownloading:(AutoDownloadImageView *)autoDowload {

    NSLog(@"OK");
}

// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	// ricaviamo il link dell'elemento selezionato
	NSString *link = [[elencoFeed objectAtIndex:indexPath.row] objectForKey: @"link"];
    NSString *titolo = [[elencoFeed objectAtIndex:indexPath.row] objectForKey: @"title"];
    NSString *path = [[elencoFeed objectAtIndex:indexPath.row] objectForKey:@"imageURL"];
    NSString *descrizione = [[elencoFeed objectAtIndex:indexPath.row] objectForKey:@"description"];

    // ripuliamo il link da spazi, return e tabs
	link = [link stringByReplacingOccurrencesOfString:@" " withString:@""];
	link = [link stringByReplacingOccurrencesOfString:@"\n" withString:@""];
	link = [link stringByReplacingOccurrencesOfString:@"	" withString:@""];
    
    // ripuliamo il link da spazi, return e tabs
    path = [path stringByReplacingOccurrencesOfString:@" " withString:@""];
	path = [path stringByReplacingOccurrencesOfString:@"\n" withString:@""];
	path = [path stringByReplacingOccurrencesOfString:@"	" withString:@""];
    NSURL *imageUrl = [NSURL URLWithString:path];
	
    // apriamo la nuova vista
    ArticoloCommentiViewController *controller =[[ArticoloCommentiViewController alloc] initWithNibName:@"ArticoloCommentiViewController" bundle:nil];
    controller.urlParserView = link;
    NSLog(@"%@", link);
    controller.titoloArticolo = titolo;
    NSLog(@"%@", titolo);
    controller.imageArticoloURL = imageUrl;
    NSLog(@"%@", imageUrl);
    controller.descrizioneArticolo = descrizione;
    NSLog(@"%@", descrizione);
    [self.navigationController pushViewController:controller animated:YES];
}


// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
   	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
    self.spinner = nil;
    self.spinnerView = nil;
}


- (void)dealloc {
	[currentElement release];
	[rssParser release];
    [URLparser release];
	[elencoFeed release];
	[item release];
	[currentTitle release];
	[currentDate release];
	[currentSummary release];
    [currentSummaryLight release];
    [currentImageUrl release];
    [currentLink release];
    [AutoDownloadImageView release];
    [spinner release];
    [spinnerView release];
    [super dealloc];
}


@end